﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
using System.IO;
using System.Data;

namespace Common.Utils
{
    public static class StringUtil
    {
        public static string GetString(MemoryStream stream)
        {
            return Encoding.UTF8.GetString(stream.ToArray());
        }

        public static MemoryStream GetStream(string value)
        {
            byte[] strbyte = Encoding.UTF8.GetBytes(value);
            MemoryStream stream = new MemoryStream(strbyte);
            return stream;
        }

        public static string GetBase64String(MemoryStream stream)
        {
            return Convert.ToBase64String(stream.GetBuffer());
        }

        public static MemoryStream GetBase64Stream(string value)
        {
            byte[] strbyte = Convert.FromBase64String(value);
            MemoryStream stream = new MemoryStream(strbyte);
            return stream;
        }

        public static void CopyStream(Stream from, Stream to, byte[] buffer)
        {
            bool flag = true;
            while (flag)
            {
                int count = from.Read(buffer, 0, buffer.Length);
                if (count > 0)
                {
                    to.Write(buffer, 0, count);
                }
                else
                {
                    to.Flush();
                    flag = false;
                }
            }
        }

        public static string Left(string value, int length)
        {
            return value.Substring(0, length);
        }

        public static string Right(string value, int length)
        {
            return value.Substring(value.Length - length);
        }

        public static string GetString(Stream stream)
        {
            if (stream is MemoryStream)
            {
                return Encoding.UTF8.GetString(((MemoryStream)stream).ToArray());
            }
            
            return "";
        }
    }
}
